<?php

/**
 *
 * @author Eivind
 *        
 */
class postClass {
	/**
	 * @var int(11) userID 
	 */
	var $usrID;
	/**
	 * DB PDO Object
	 * @var PDO
	 */
	var	$db;
	/**
	 * 
	 * @param int(11) $usrID User ID
	 * @param PDO $db PDO DB Object
	 */
	function __construct($usrID, $db){
		$this -> usrID = $usrID;
		$this -> db = $db;
	}
	/**
	 * Get all user post from today and $days backwards, NOT showing post that have been deleted by admin and user
	 * @param boolean $public If the post are public, 
	 * @return string
	 */
	function getLastPosts ($limit) {
		$query = "SELECT postId, post, userID, author, postTitle, DATE_FORMAT( `timeCreated` , '%d %b %Y %H:%i' ) AS time 
				FROM post JOIN user on author = userName
				WHERE statusCode NOT LIKE 'D%' AND isBlocked NOT LIKE 1
				ORDER BY timeCreated DESC
				LIMIT :limit";
		$result = $this -> db -> prepare ($query);
		$result ->bindValue(':limit', (int) $limit, PDO::PARAM_INT);
		echo "<h2>Siste {$limit} innlegg</h2>";
		$result -> execute ();		
		while ($row = $result -> fetch()) {
			$intro = preg_replace('/<[^>]*>/', '', $row['post']);
			$intro = substr($intro, 0, 20);
			echo "<div class='blogpost'>
			<img src='include/displayFile.php?usrID={$row['userID']}' />
			<h3><a href='showPost.php?id={$row['postId']}'>{$row['postTitle']}</h3></a>
			<p id='intro'>{$intro}...</p>
			<h4>Skrevet av: <a href='displayUsr.php?usrName={$row['author']}'>{$row['author']}</a></h4>
			<p>Publisert {$row['time']}</p>
			</div>";
		}
	}
	
	function getPostMostRead($days){
		$query = "";
		$result = $this -> db -> prepare($query);
		$result -> execute();
	}
	/**
	 * Display one uniqe post with a link to edit if the author is the user that is logged in
	 * and increment  by 1
	 * @param int $postID 
	 * @param bool $isAdmin True if user is admin 
	 * @return string html code to display post
	 */
	 function displayPost($postID, $isAdmin){
        $query ='SELECT userID, 
	 					postTitle, 
	 					post, 
	 					DATE_FORMAT( `timeCreated` , "%d %b %Y %H:%i" ) AS time,
						timeLastEdited,
	 					userName,
        				statusCode,
						user.isBlocked AS blocked, description
	 			FROM post, user, statusCode AS c
	 			WHERE post.author=user.userName AND c.code=statuscode AND post.postId=:id;';
	 	$result = $this ->  db -> prepare($query);
	 	$result -> bindParam (':id', $postID);
	 	$result -> execute();
	 	$res = $result -> fetch();
		
		if($res['blocked']) { // User is blocked
			echo "<h2>{$res['postTitle']}</h2><br />
	 		<div id='blogpost'><p><i>Forfatteren av dette innlegget er blokkert av administrator</i></p><br />";
	 		if($isAdmin){
	 			echo $res['post']."<br />"; 	// Admin can still read post
	 		}
	 		echo "</div>";
		}else if($res['statusCode'] == 'DA'){ 		//Deleted by admin, notify reader, and dont show post
	 		echo "<h2>{$res['postTitle']}</h2><br />
	 		<div id='blogpost'><p><i>{$res['description']}</i></p><br />";
	 		if($isAdmin){
	 			echo $res['post']."<br />"; 	// Admin can still read deleted post
	 		}
	 		echo "</div>";
	 	}else if($res['statusCode'] == 'DO'){ 	// Deleted by Owner, notify reader, and dont show post
	 		echo "<h2>{$res['postTitle']}</h2><br />
	 		<div id='blogpost'><p><i>{$res['description']}</i></p><br />";
	 		echo "</div>";
		}else{
			echo "<h2>{$res['postTitle']}</h2>";
		 	if($this -> usrID == $res['userID']){ 	//If author is logged in he can edit post
		 		echo "<a class='icon' href='editPost.php?postId=$postID'>
		 		<img src='include/img/24_Edit.png' title='Rediger innlegg'>
		 		</a>";
		 	}
		 	if($this -> usrID == $res['userID'] || $isAdmin){ //if admin or author is logged in they can delete post
		 		echo "<form class='icon' method='post' action='showPost.php?id={$postID}'>
				<input type='hidden' name='pid' value='{$postID}' />
		 		<input type='image' src='include/img/RecycleBin.png' name='delete' 
		 		value='delete' OnClick=\"return confirm('Er du sikker på at du vil slette dette innlegget?');\"
		 		title='Slett dette innlegget'/>
		 		</form>";
		 	} 									//Show post to reader
			if($this -> usrID != $res['userID']) {
				echo "<form class='icon' method='post' action='showPost.php?id={$postID}'>
	 			<input type='hidden' name='pid' value='{$postID}' />
	 			<input type='image' src='include/img/16_Cancel.png' title='Merk dette innlegget som upassende'/>
	 			</form>";
			}
		 	
		 	echo "<div id='blogpost'>{$res['post']}</div>
				<div id='pubedit'><p>";
			if($res['timeLastEdited'] == "0000-00-00 00:00:00") {
				echo "Publisert: {$res['time']}";
			}
			else {
				echo "Editert: ".date('j M Y H:i',strtotime($res['timeLastEdited']));
			}	
			echo "</p>
		 	</div>";	 
	  	}
	 }
	 /**
	  * Inserting post to DB
	  * @param string $postTitle 
	  * @param string $post
	  * @param string $userName 
	  */
	 function insertPost($postTitle, $post, $userName){
	 	$src = $_SERVER['DOCUMENT_ROOT'].'/media/'; //Default media location on upload
	 	$dest = $_SERVER['DOCUMENT_ROOT'].'/media/'.$this -> usrID."/"; //User uniqe folder, with their media
	 	try{
		 	$this -> db -> beginTransaction();
		 	$this -> db -> query('LOCK TABLES post WRITE');
		 	$sql = "INSERT INTO post (author, postTitle, post)
				 VALUES (:author, :postTitle, :post)";
		 	$sth = $this -> db -> prepare ($sql);
		 	$sth->bindParam (':author', $userName);
		 	$sth->bindParam (':postTitle', $postTitle);
		 	$newPost = str_replace($src, $dest, $post); 	//Edit media links in post to user uniqe folder
		 	$sth->bindParam (':post', $newPost);
		 	$sth->execute ();
		 	$sth -> closeCursor();
		 	$sth = $this -> db -> prepare('SELECT LAST_INSERT_ID() AS postID');
		 	$sth -> execute();
		 	if($sth -> rowCount() == 0){
		 		$this -> db -> rollBack();
		 		$this -> db -> query('UNLOCK TABLES');
		 		throw new Exception('Unable to save post!');
		 	}
		 	$sth = $sth -> fetch();
		 	//Moves all uploaded files files to user media folder
		 	if(is_dir($dest)){
		 		$files = scandir($src);
		 		foreach($files as $file){
		 			if(in_array($file, array(".","..","listImg.php"))){
		 				continue;
		 			}
		 			rename($src.$file, $dest.$file);
		 		}
		 	}
		 	$this -> db -> commit();
		 	return $sth['postID'];
		}catch (Exception $e){
	 		$this -> db -> rollBack();
	 		echo 'Feil når innlegget ble forsøkt lagret '.$e->getMessage();
	 	}
 	}
		 
	 /**
	  * Updating post in DB
	  * @param array $post formdata
	  */
	 function editPost($post){
		$src = $_SERVER['DOCUMENT_ROOT'].'/media/';
		$dest = $_SERVER['DOCUMENT_ROOT'].'/media/'.$this -> usrID."/";
		
		// Updates post in DB
		$sql = "UPDATE post SET postTitle=:postTitle, timeLastEdited=now(), post=:post WHERE postId = :postId";
		$sth = $this->db->prepare ($sql);
		$sth->bindParam (':postId', $post['id']);
		$sth->bindParam (':postTitle', $post['postTitle']);
		$newPost = str_replace($src, $dest, $post['post']);
		$sth->bindParam (':post', $newPost);
		$sth->execute ();
	
		//Flytter filer som er lastet opp til brukes mappe på server til senere bruk
		if(is_dir($dest)){
			$files = scandir($src);
			foreach($files as $file){
				if(in_array($file, array(".","..","listImg.php"))){
					continue;
				}
			rename($src.$file, $dest.$file);
			}
		}	
	}
	 
	 
	 /**
	  * returns a article foreach post made by $usrName
	  * @param string $usrName
	  * @return string blogg post article foreach post made by a uniqe user
	  */
	 function getPostUsr($usrName, $isAdmin){
	 	$query ='SELECT postId,
	 					post,
	 					postTitle,
	 					statusCode,
	 					DATE_FORMAT( `timeCreated` , "%d %b %Y %H:%i" ) AS time,
						isBlocked
				FROM post, user 
	 			WHERE author=userName AND author=:usrName
				ORDER BY timeCreated DESC';
	 	$result = $this ->  db -> prepare($query);
	 	$result -> bindParam (':usrName', $usrName);
	 	$result -> execute();
	 	while($res = $result -> fetch()){
			if($res['isBlocked']) { // If user/author is blocked do not display
				continue;
			}						// If user is NOT admin, dont display deleted posts
			elseif(!$isAdmin && $res['statusCode']=='DO' || $res['statusCode']=='DA') { 				
	 			continue;
	 		}
			else { 					// Display post article
	 			$intro = preg_replace('/<[^>]*>/', '', $res['post']);
	 			$intro = substr($intro, 0, 20);
	 			echo "<div class='blogpost'>
	 			<h3><a href='showPost.php?id={$res['postId']}'>
	 			{$res['postTitle']}</a></h3>". //If post are deleted, admin will be get the message
	 	 			(($res['statusCode']=='DO' || $res['statusCode']=='DA')?
	 	 					"<p id='intro'>Slettet</p>":"<p id='intro'>{$intro}...</p>")."
	 					
	 					<p>Publisert {$res['time']}</p>
	 					</div>";	 			
	 		}
	 	}
	 }
	 
	 /**
	  * Updates number of reports in DB and mark the post as a MP (marked post)
	  * @param int $pid Post id
	  * @return string 
	  */
	 function flaggPost($pid){
	 	$query = "UPDATE post SET numberOfFlags = numberOfFlags + 1, statusCode='MP' WHERE postId=:id";
	 	$result = $this -> db -> prepare($query);
	 	$result -> bindParam(':id', $pid);
	 	$result -> execute();
	 	return "Innlegget har blitt rapportert inn til Administrator!";
	 }
	 
	/**
	 * Echos out html to generate a comment field foreach comment that belongs to $postId
	 * Based on the user is a admin, the comment owner, or the post owner the comments will have different options to
	 * administer the/all comment(s)
	 * @param int $postId
	 * @param bool $isAdmin
	 * @param string $userName
	 * @param int $cid CommentId
	 */
	function getComments($postId, $isAdmin, $userName, $cid){
		$query = 'SELECT c.id, c.commentAuthor, c.userName, c.comment, c.commentStatus, c.published, s.description, p.author
					FROM comments AS c, post AS p, statusCode AS s 
					WHERE c.postId=:postId  AND p.postId=c.postId AND c.commentStatus=s.code
					ORDER BY published';
	 	$result  = $this -> db -> prepare($query);
	 	$result -> bindParam(':postId', $postId);
	 	$result -> execute();
	 	while($res = $result -> fetch()){
	 		echo "<div class='comment' id={$res['id']}>";
	 		echo $res['published']." Skrev ";
	 		echo (!is_null($res['userName']))?"<a href='displayUsr.php?usrName={$res['userName']}'>{$res['userName']}:</a>":"{$res['commentAuthor']}:";
	 		// Show the delete-button where apropriate:
			if((isset($userName) && $res['userName'] == $userName && $res['commentStatus']!='CDA' && $res['commentStatus']!='CDO')
			   || ($isAdmin && $res['commentStatus'] == 'MC' && $res['commentStatus']!='CDA' && $res['commentStatus']!='CDO')
			   || (isset($userName) && $res['author'] == $userName && $res['commentStatus']!='CDA' && $res['commentStatus']!='CDO')){
		 		echo "<form method='post' action='showPost.php?id={$postId}'>
		 		<input type='hidden' name='cid' value='{$res['id']}' />
		 		<input type='hidden' name='delete' value='true' />
		 		<input type='image' src='include/img/16_recyclebin.png' title='Slett denne kommentaren'/>
		 		</form>";
			// Show report button if not deleted:
	 		}elseif($res['commentStatus']!='CDA' && $res['commentStatus']!='CDO'){
	 			echo "<form method='post' action='showPost.php?id={$postId}'>
	 			<input type='hidden' name='cid' value='{$res['id']}' />
	 			<input type='image' src='include/img/16_Cancel.png' title='Merk denne kommentaren som upassende'/>
	 			</form>";	 		
		 	}
			// Comment deleted show delete description:
			if($res['commentStatus']=='CDA' || $res['commentStatus']=='CDO'){
	 			echo "<p><i>".$res['description']."</i></p></div>";
	 		}else{
	 			if($isAdmin && $res['commentStatus'] == 'MC'){
	 				if(!is_null($cid) && $cid == $res['id']){
	 					echo "<p style='color:red;'>".$res['comment']."</p></div>";
	 				}else{
	 					echo "<p style='color:orange;'>".$res['comment']."</p></div>";
	 				}
	 			}else{
	 				echo "<p>".$res['comment']."</p></div>";
	 			}
	 		}
	 	}
	 }
	 
	 /**
	  * Updates number of reports in DB and mark the comment as a MC (marked comment)
	  * @param int $cid Comment id
	  * @return string 
	  */
	 function flaggComment($cid){
	 	$query = "UPDATE comments SET numberOfFlags = numberOfFlags + 1, commentStatus='MC' WHERE id=:id";
	 	$result = $this -> db -> prepare($query);
	 	$result -> bindParam(':id', $cid);
	 	$result -> execute();
	 	return "Kommentaren har blitt rapportert inn til Administrator!";
	 }
	 
	 /**
	  * Echos out htmlcode to create a form to make a new comment
	  * @param int $postId Post ID
	  * @return void newComment form
	  */
	 function newComment($postId, $userId){
	 	echo "<div id='newComment'>
	 	<form method='post' action='showPost.php?id={$postId}' id='userComment'>";
	 	if(is_numeric($userId)){
	 		echo "<input type='hidden' name='author' value='{$userId}' />";
	 	}else{
	 		echo "<input type='text' placeholder='Name' name='author' />";
	 	}
	 	echo "<textarea name='comment' cols='60' rows='5' placeholder='Skriv inn ny kommentar....'></textarea><br />";
		require_once('recaptchalib.php');
        $publickey = "6LeG6e8SAAAAAMVwYvKh6gbQtS1Uw_ibozLnpz9f";
		echo recaptcha_get_html($publickey);
		echo "<input type='submit' value='Post kommentar' />
	 	</form> 
	 	</div>";
	 }
	 
	 /**
	  * Inserts new comment to DB
	  * @param multitype $author Is either a int(userid) if a user is logged in
	  * or a text string if a public user makes a comment
	  * @param string $comment The comment
	  * @param int $postId The post the comment is bound to
	  * @param boolean $online True if a user is logged in
	  * @return boolean true if DB insert is okey and false if not
	  */
	 function insertComment($author, $comment, $postId, $online){
	 	if(is_numeric($author) && $online){
	 		$query = "INSERT INTO comments (postId, userName, comment) VALUES
	 				(:postId, (SELECT userName FROM user WHERE userID =:author), :comment)";
	 	}else{
	 		$query = "INSERT INTO comments (postId, commentAuthor, comment) VALUES
	 				(:postId, :author, :comment)";
	 	}
	 	$result = $this -> db -> prepare($query);
	 	$result -> bindParam(':postId', $postId);
	 	$result -> bindParam(':author', $author);
	 	$result -> bindParam(':comment', $comment);
	 	$res = $result -> execute();
	 	return $res;
	 }
	 /**
	  * 
	  * @param int $cid Commentid
	  * @param bool $isAdmin Is user admin
	  * @return string Respons message based on the comment did get deleted successfully or not
	  */
	 function deleteComment($cid, $isAdmin){
	 	if(!$isAdmin){
	 		$query = "UPDATE comments SET commentStatus='CDO' WHERE id =:cid";	 		
	 	}else{
	 		$query = "UPDATE comments SET commentStatus='CDA' WHERE id =:cid";	 		
	 	}
	 	$result = $this -> db -> prepare($query);
	 	$result -> bindParam(":cid", $cid);
	 	$result -> execute();
	 	return (($result -> execute()) ? "Kommentar har blitt slettet!" : "En feil oppsto, kommentar er ikke slettet!");
	 }
	 /**
	  * Get a post from DB, using the $postID as key
	  * @param int $postID
	  * @return multitype:array mixed {posttitle,post}
	  */
	 function getEditInfo($postID){  		// Getting post from DB
	 	$query = 'SELECT postTitle, post FROM post WHERE postId=:id;';
	 	$sth = $this -> db -> prepare($query);
	 	$sth -> bindParam (':id', $postID);
	 	$sth -> execute();
	 	$row = $sth->fetch();
	 	if($row){
	 		return array($row['postTitle'], $row['post']);
	 	}
	 }
	/**
	 * Marks post as deleted in DB, based on who that deletes it
	 * @param int $postId on post to delete
	 * @param bool $isAdmin if user is a Admin
	 */
	function deletePost($postId, $isAdmin){
		if(!$isAdmin){ //Security check on that $user is realy the user that made the post
						// DO = Deleted by Owner, DA = Deleted by Administrator
			$query = "UPDATE post SET statusCode='DO' WHERE postId =:postId 
					AND author = (select userName From user where userID =:usrId)";
			$result = $this -> db -> prepare($query);
			$result -> bindParam(':usrId', $this -> usrID);
		}else{
			$query = "UPDATE post SET statusCode='DA' WHERE postId =:postId";
			$result = $this -> db -> prepare($query);
		}
		$result -> bindParam(':postId', $postId);
		return ($result -> execute())? "Innlegget ble nå markert som slettet!" : "En feil oppsto, innlegget har ikke blitt markert som slettet!";
		
	}
	/**
	 * Calculateing top 10 users and echo out a top 10 list of it
	 */
function top10(){
		// Getting user that has the most commented and viewed post for the last 14 days
		$query = "SELECT post.author as username
			FROM view_getCounter 
			LEFT JOIN post ON view_getCounter.siteId = post.postid
			LEFT JOIN user ON post.author = user.username
			WHERE user.isblocked = 0 AND post.statusCode NOT LIKE 'D%'
			GROUP BY post.author
			ORDER BY SUM(view_getCounter.twoWeekBack) DESC, COUNT(view_getCounter.site) ASC";
		$results = $this -> db -> prepare($query);
		$results -> execute();
		
	 	echo "<ol id='top10'>";
	 	while($total = $results -> fetch()){
	 		echo "<li><a href='displayUsr.php?usrName={$total['username']}'>{$total['username']}</a></li>";	 		
	 	}
		echo "</ol>";
	}	
	/*
	 * Gets authour of post
	 * @param int $postID ID of post
	 * @return sting Author name (userName)
	*/
	function getAuthor($postID) {
		$query = 'SELECT author FROM post WHERE postId=:id;';
	 	$sth = $this -> db -> prepare($query);
	 	$sth -> bindParam (':id', $postID);
	 	$sth -> execute();
	 	$row = $sth->fetch();
	 	return $row['author'];
	}
}
?>